/*
 * Author Hung Tran
 */
package viettravel.guiandevent.place;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;

import org.holoeverywhere.app.ProgressDialog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import viettravel.DAO.FriendDAO;
import viettravel.common.Constants;
import viettravel.guiandevent.R;
import viettravel.guiandevent.map.DirectionListActivity;
import viettravel.guiandevent.map.search.GGDataReader;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

public class FriendListsNearLocation extends SherlockActivity{
	   
	private ArrayList<FriendDAO> mFriendLists;
	private FriendListsAdapter mFriendListsAdapter;
	private ListView lvFriendLists;
	private String mPlaceName;
	private String mPlaceLatlng;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(Constants.THEME);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_friendlists);

		ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		actionBar.setDisplayHomeAsUpEnabled(false);
		actionBar.setHomeButtonEnabled(true);
		actionBar.setIcon(R.drawable.ic_back_arrow);
		actionBar.setTitle(getString(R.string.friendlists_title));
		actionBar.setBackgroundDrawable(Constants.APP_DRAWABLE);
		mFriendLists = new ArrayList<FriendDAO>();
		lvFriendLists = (ListView)findViewById(R.id.friendListNearLocation);
		lvFriendLists.setOnItemClickListener(listFriendItemClickListener);
		Bundle extra = getIntent().getExtras();
		try{
			mPlaceName = extra.getString(Constants.EXTRA_PLACE_NAME);
			Log.v(Constants.TAG, mPlaceName);
			mPlaceLatlng = extra.getString(Constants.EXTRA_PLACE_LAT);
			Log.v(Constants.TAG, mPlaceLatlng);
			//mPlaceLng = extra.getDouble(Constants.EXTRA_PLACE_LONG);
			
			JSONArray jFriendLists = new JSONArray(extra.getString(Constants.EXTRA_GETFRIEND));
			for ( int i = 0; i < jFriendLists.length(); i++){
				JSONObject friend = jFriendLists.getJSONObject(i);
				JSONObject fLocation = friend.getJSONObject(Constants.TAG_FB_CURRENT_LOCATION);
				Drawable fImage = LoadImageFromWebOperations(friend.getString(Constants.TAG_FB_PIC_SQU));
				FriendDAO fDao = new FriendDAO(fImage,
						friend.getString(Constants.TAG_FB_NAME),
						fLocation.getString(Constants.TAG_FB_NAME),
						fLocation.getDouble(Constants.TAG_FB_LATITUE),
						fLocation.getDouble(Constants.TAG_FB_LONGTITUTE));
				mFriendLists.add(fDao);
				
			}
			Log.v(Constants.TAG, mFriendLists.size()+"");
			mFriendListsAdapter = new FriendListsAdapter(this, mFriendLists);
			lvFriendLists.setAdapter(mFriendListsAdapter);
		}catch(JSONException e){
			Log.v(Constants.TAG, "Loi day ne");
		}
		
		
    }

    OnItemClickListener listFriendItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			FriendDAO f = mFriendLists.get(position);
			Log.v(Constants.TAG, f.getName());
			Log.v(Constants.TAG, f.getAddress());
			Log.v(Constants.TAG, f.getLatitude()+ "," + f.getLongtitude());
			
			StringBuilder urlBuilder =new StringBuilder();
			urlBuilder.append("http://maps.googleapis.com/maps/api/directions/json?origin=");
			String startLocation= mPlaceLatlng;
			urlBuilder.append(startLocation);
			urlBuilder.append("&destination=");
			String endLocation = f.getLatitude()+ "," + f.getLongtitude();
			urlBuilder.append(endLocation);
			urlBuilder.append("&sensor=false&units=metric&language=vi");
			urlBuilder.append("&mode=");
			urlBuilder.append("driving");
			Log.d(Constants.TAG+"URL", urlBuilder.toString());
			new Direction().execute(urlBuilder.toString());			
		}
	};
	@Override
	public boolean onCreateOptionsMenu(Menu _menu) {
        return super.onCreateOptionsMenu(_menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:{
			finish();
            return true;
		}
		default:
			return super.onMenuItemSelected(featureId, item);
		}
	}
	
	private Drawable LoadImageFromWebOperations(String url) {
	    try {
	        InputStream is = (InputStream) new URL(url).getContent();
	        Drawable d = Drawable.createFromStream(is, "src name");
	        return d;
	    } catch (Exception e) {
	        return null;
	    }
	}
	
public class Direction extends AsyncTask<String, Integer, String>{
		
		private ProgressDialog mProgressDialog;

		@Override
		protected void onPreExecute() {
			mProgressDialog = new ProgressDialog(FriendListsNearLocation.this);
			mProgressDialog.setMessage("Get direction");
			mProgressDialog.setCancelable(false);
			mProgressDialog.setIndeterminate(true);
			mProgressDialog.show();
		};

		@Override
		protected String doInBackground(String... params) {
			JSONObject jsonObject = GGDataReader.getJsonFromUrl(params[0]);
			try {
				if (jsonObject.getString(Constants.TAG_STATUS).equals("OK")) {
					return jsonObject.toString();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return "FAIL";
		}
		@Override
		protected void onPostExecute(String result)
		{
			if (mProgressDialog.isShowing()) 
			{
				mProgressDialog.dismiss();
				if(!result.equals("FAIL")){
					Intent intent=new Intent(getBaseContext(),DirectionListActivity.class);
					intent.putExtra(Constants.DIRECTIONLIST, result);
					intent.putExtra(Constants.TAG_PLACES_NAME, mPlaceName);
					Log.d("GET DIRECTION", result);
					startActivity(intent);
				}
			}
		}		
	}
}
